package com.hbue.springboot.Interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.hbue.springboot.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.http.HttpMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import com.hbue.springboot.pojo.Result;

import static com.hbue.springboot.utils.ResultCode.TOKEN_ERROR;

/**
 * 功能：
 * 日期：2025/1/13 13:52
 */
@Slf4j
public class JWTInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String servletPath = request.getServletPath();
        String contextPath = request.getContextPath();
        log.info("servletPath = "+servletPath);
        log.info("contextPath = "+contextPath);
        log.info("request header token = "+token);
        // 浏览器在正式跨域请求发起之前的预检请求
        String method = request.getMethod();
        String httpMethod = HttpMethod.OPTIONS.toString();
        log.info("method = "+method);
        log.info("httpMethod = "+httpMethod);
        // 条件成立：当请求方式为OPTIONS直接放行
        if (Objects.equals(method, httpMethod)) {
            log.info("OPTIONS请求，直接放行");
            return true;
        }
        // 当JWT认证失败，返回给前端的信息
        String msg;
        try {
            JWTUtils.verify(token);

            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            msg = "无效签名";
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            msg = "token过期";
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            msg = "token算法不一致";
        } catch (Exception e) {
            e.printStackTrace();
            msg = "token无效";
        }

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(new Result(TOKEN_ERROR, msg));
        return false;
    }
}